package com.jts.cloudspokes;

import java.io.IOException;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.xmpp.JID;
import com.google.appengine.api.xmpp.Message;
import com.google.appengine.api.xmpp.MessageBuilder;
import com.google.appengine.api.xmpp.MessageType;
import com.google.appengine.api.xmpp.Presence;
import com.google.appengine.api.xmpp.XMPPService;
import com.google.appengine.api.xmpp.XMPPServiceFactory;
import com.jts.cloudspokes.datastore.BotDSManager;
import com.jts.cloudspokes.entities.BotTaskEntity;
import com.jts.cloudspokes.util.BotUtility;

@SuppressWarnings("serial")
public class TaskDeliveryServlet extends HttpServlet {
	
	private static final XMPPService xmppService = XMPPServiceFactory.getXMPPService();
	private static final Logger logger = Logger.getLogger(TaskDeliveryServlet.class.getName());
	private static final BotDSManager botDSManager = new BotDSManager();
	
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
		throws IOException {
		logger.warning("Reached task queue");
		String paramTaskId = req.getParameter(BotConstants.PARAM_TASK_ID);
		botDSManager.startPersistenceManager();
		BotTaskEntity bteObj = botDSManager.fetchTaskFromDSByKey(paramTaskId);
		if (bteObj != null) {
			String userId = bteObj.getUserId();
			String toMailId = BotUtility.getActualEmailId(userId);
			JID toJid = new JID(userId);
			Message messageToSend = new MessageBuilder()
										.withMessageType(MessageType.CHAT)
										.withRecipientJids(toJid)
										.withBody(bteObj.getTaskMessage())
										.build();
			xmppService.sendMessage(messageToSend);
			logger.info("message sent");
			/* if user is not available then send a mail */
			Presence userPresenceStatus = xmppService.getPresence(toJid);
			if (!userPresenceStatus.isAvailable()) {
				Properties properties = new Properties();
				Session session = Session.getDefaultInstance(properties, null);
				try {
					MimeMessage emailMessage = new MimeMessage(session);
					emailMessage.setFrom(new InternetAddress("todotaskbot.mailer@gmail.com", "TODO Task BOT"));
					
					emailMessage.addRecipient(RecipientType.TO, new InternetAddress(toMailId));
					emailMessage.setSubject(bteObj.getTaskMessage());
					emailMessage.setText("Your task :" + bteObj.getTaskMessage() + " is due."
							+ "\n" + "This task was created at " + bteObj.getTaskDate());
					Transport.send(emailMessage);
				} catch (AddressException e) {
					e.printStackTrace();
					logger.log(Level.SEVERE, "Mail was not sent to " + toMailId + "\n"
							+ e.getMessage());
				} catch (MessagingException e) {
					e.printStackTrace();
					logger.log(Level.SEVERE, "Mail was not sent to " + toMailId + "\n"
							+ e.getMessage());
				}
			}
			/* delete the task entry from db */
			botDSManager.deleteTask(userId, paramTaskId);
		}
		botDSManager.stopPersistenceManager();
	}
}
